package chatNI;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.DatagramPacket;
import java.util.concurrent.Semaphore;

import chatController.ChatController;
import cs.remoteapp.Message;

/**
 * <b>Project ChatSystemG2 - INSA 4INFOA1 - 2013/2014</b>
 * <P>
 * <i>Package  chatNI</i> <br>
 * ReceiveThread is the part of the chatNI that is related to the reception thread. <br>
 * It extends Thread. 
 *
 * @author Sergio Gonzalez - Marie-Charlotte Bideaud
 */

public class ReceiveThread extends Thread {

	private ChatController controller;
	private DatagramPacket packet;
	private static Semaphore semaphore;
	
	/**
	 * Constructor for the class ReceiveThread
	 * 
	 * @param packet : DatagramPacket
	 * @param controller : ChatController
	 */
	public ReceiveThread (DatagramPacket packet, ChatController controller) {
		this.packet = packet;
		this.controller = controller;
		semaphore = new Semaphore(1);
	}
	
	/**
	 * Method starting the thread
	 */
	public void run () {
		try {
			semaphore.acquire();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try {
			ByteArrayInputStream bis = new ByteArrayInputStream(packet.getData());
			ObjectInputStream ois = new ObjectInputStream(bis);
			Object object = ois.readObject();
			if (object instanceof Message) {
				controller.selectProcess((Message)object, packet.getAddress());
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		semaphore.release();
	}
	
}
